package com.lin.controller.admin;

import com.lin.common.constant.JwtClaimsConstant;
import com.lin.common.context.BaseContext;
import com.lin.common.properties.JwtProperties;
import com.lin.common.result.Result;
import com.lin.common.utils.JwtUtil;
import com.lin.entity.Admin;
import com.lin.entity.vo.AdminVo;
import com.lin.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/admin")
@Api(tags = "管理员相关接口")
@Slf4j
public class AdminController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录
     * @param admin
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<AdminVo> loginUser(@RequestBody Admin admin) {
        log.info("管理员登录：{}",admin);
        //登录成功后，生成jwt令牌
        loginService.loginAdmin(admin);;
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(admin,adminVo);
        adminVo.setToken(token);
        BaseContext.setCurrentId(admin.getId());
        return Result.success(adminVo);
    }
}
